package com.hulk.rpc.loadbalance.impl;

import cn.hutool.core.collection.CollUtil;
import com.hulk.rpc.loadbalance.LoadBalance;
import com.hulk.rpc.loadbalance.Weightable;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询算法
 *
 * @author xuxukang
 * @date 2019-03-27 17:32
 */
public class RoundRobinLoadBalance<T extends Weightable> extends LoadBalance<T> {

  private static final AtomicInteger tryCounter = new AtomicInteger();

  @Override
  public T select() {
    if (CollUtil.isEmpty(resources)) {
      return null;
    }

    int counter = tryCounter.getAndIncrement();
    // 避免溢出
    if (counter >= resources.size()) {
      tryCounter.set(0);
    }
    return resources.get(counter);
  }

  @Override
  public void clean() {
    tryCounter.set(0);
  }
}
